import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:keyboard_avoider/keyboard_avoider.dart';

class ForgotPassword extends StatelessWidget {
  final String uniqueId;
  //初始化函数
  ForgotPassword({Key key, @required this.uniqueId}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        automaticallyImplyLeading: false, // 去除返回按钮
        title: Text('找回密码'),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: Theme(
        data: Theme.of(context).copyWith(
          primaryColor: Colors.black,
        ),
        child: Container(
            padding: EdgeInsets.all(16.0),
            child: KeyboardAvoider(
              autoScroll: true,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  ForgotPasswordForm(uniqueId: this.uniqueId),
                ],
              ),
            )),
      ),
    );
  }
}

class ForgotPasswordForm extends StatefulWidget {
  final String uniqueId;
  //初始化函数
  ForgotPasswordForm({Key key, @required this.uniqueId}) : super(key: key);
  @override
  ForgotPasswordFormState createState() =>
      ForgotPasswordFormState(uniqueId: this.uniqueId);
}

class ForgotPasswordFormState extends State<ForgotPasswordForm> {
  // 验证码倒计时
  Timer _timer;
  int _countdownTime = 0;
  // 设备唯一id
  String uniqueId;
  //初始化函数
  ForgotPasswordFormState({Key key, @required this.uniqueId});
  final forgotPasswordFormKey = GlobalKey<FormState>();
  String username, email, code, newPassword;
  bool autovalidate = false;

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  void submitForgotPasswordForm() {
    if (forgotPasswordFormKey.currentState.validate()) {
      forgotPasswordFormKey.currentState.save();
      this.fetchPosts(username, email, code, newPassword);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  // 倒计时
  void startCountdownTimer() {
    const oneSec = const Duration(seconds: 1);
    var callback = (timer) => {
          setState(() {
            if (_countdownTime < 1) {
              _timer.cancel();
            } else {
              _countdownTime = _countdownTime - 1;
            }
          })
        };
    _timer = Timer.periodic(oneSec, callback);
  }

  void getEmailCodeForm() {
    forgotPasswordFormKey.currentState.save();
    if (username == '') {
      Fluttertoast.showToast(
          msg: '请输入用户名！',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
      return;
    }
    if (email == '') {
      Fluttertoast.showToast(
          msg: '请输入邮箱！',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
      return;
    }
    if (_countdownTime == 0) {
      //Http请求发送验证码
      this.fetchSendEmailCode(username, email);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
      setState(() {
        _countdownTime = 60;
      });
      //开始倒计时
      startCountdownTimer();
    }
  }

  String validateRequired(value) {
    if (value.isEmpty) {
      return '请正确填写此字段！';
    }

    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: forgotPasswordFormKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            decoration: InputDecoration(
              labelText: '用户名',
              helperText: '',
            ),
            onSaved: (value) {
              username = value;
            },
            validator: validateRequired,
          ),
          TextFormField(
            keyboardType: TextInputType.emailAddress,
            decoration: InputDecoration(
              labelText: '绑定邮箱',
              helperText: '',
            ),
            onSaved: (value) {
              email = value;
            },
            validator: validateRequired,
          ),
          TextFormField(
            decoration: InputDecoration(
              labelText: '邮箱验证码',
              helperText: '',
              suffixIcon: TextButton(
                  // color: Theme.of(context).accentColor,
                  child: Text(
                      _countdownTime > 0 ? '$_countdownTime s后重新获取' : '获取邮箱验证码',
                      style: TextStyle(fontSize: 18)),
                  onPressed: () {
                    getEmailCodeForm();
                  }),
            ),
            onSaved: (value) {
              code = value;
            },
            validator: validateRequired,
          ),
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: '设置新密码',
              helperText: '',
            ),
            onSaved: (value) {
              newPassword = value;
            },
            validator: validateRequired,
          ),
          SizedBox(
            height: 32.0,
          ),
          Container(
            width: double.infinity,
            child: ElevatedButton(
              // color: Theme.of(context).accentColor,
              child: Text('确认', style: TextStyle(color: Colors.white)),
              onPressed: submitForgotPasswordForm,
            ),
          ),
          SizedBox(
            height: 32.0,
          ),
          Container(
              width: double.infinity,
              child: Row(
                children: <Widget>[
                  Text('想起密码，去'),
                  TextButton(
                    style: ButtonStyle(
                        // foregroundColor: Theme.of(context).accentColor, //字体颜色
                        elevation: MaterialStateProperty.all(0)),
                    child: Text('登录',
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.w500)),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ],
              )),
        ],
      ),
    );
  }

  // 发送验证码到邮箱
  Future fetchSendEmailCode($username, $email) async {
    var dataBody = jsonEncode(
        {'username': $username, 'email': $email, 'deviceId': uniqueId});
    final response = await http.post(
        'https://me.yuanqiao.pw/api/me/send-email-code.php',
        body: dataBody);
    EasyLoading.dismiss();
    print('汗发烧发生的范德萨');
    print(response.statusCode);
    print(response.body);
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      print('responseBody');
      print(responseBody);
      var state = responseBody['state'];
      if (state == '1') {
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
      } else {
        if (mounted) {
          setState(() {
            if (_timer != null) {
              _timer.cancel();
            }
            _countdownTime = 0;
          });
        }
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
      }
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }

  Future fetchPosts($username, $email, $code, $newPassword) async {
    var dataBody = jsonEncode({
      'username': $username,
      'email': $email,
      'code': $code,
      'newPassword': $newPassword,
      'deviceId': uniqueId
    });
    final response = await http.post(
        'https://me.yuanqiao.pw/api/me/find-password.php',
        body: dataBody);
    EasyLoading.dismiss();
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      print('responseBody');
      print(responseBody);
      var state = responseBody['state'];
      if (state == '1') {
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
        Navigator.of(context).pushNamedAndRemoveUntil(
          '/login',
          (route) => route == null,
        );
      } else {
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
      }
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }
}
